package tech.aistar.prj.listener;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpSessionAttributeListener;
import javax.servlet.http.HttpSessionBindingEvent;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

public class CountOnlineListener implements HttpSessionListener, HttpSessionAttributeListener {
    private Integer count=0;
    @Override
    public void sessionCreated(HttpSessionEvent httpSessionEvent) {
      ServletContext app=httpSessionEvent.getSession().getServletContext();
      synchronized (this){
          count++;
          System.out.println("进来"+count+"人");
          app.setAttribute("online",count);
      }
    }

    @Override
    public void sessionDestroyed(HttpSessionEvent httpSessionEvent) {

    }

    @Override
    public void attributeAdded(HttpSessionBindingEvent httpSessionBindingEvent) {

    }

    @Override
    public void attributeRemoved(HttpSessionBindingEvent httpSessionBindingEvent) {
        System.out.println("走掉一个人...");
        ServletContext app = httpSessionBindingEvent.getSession().getServletContext();
        synchronized (this) {
            count--;
            System.out.println("走了,还剩:"+count+"人");
            app.setAttribute("online", count);
        }
    }

    @Override
    public void attributeReplaced(HttpSessionBindingEvent httpSessionBindingEvent) {

    }
}
